package com.sangeng.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sangeng.domain.dto.AssignRolePermissionsDTO;
import com.sangeng.domain.entity.role.PermissionRole;
import com.sangeng.mapper.PermissionRoleMapper;
import com.sangeng.service.IPermissionRoleService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class PermissionRoleServiceImpl extends ServiceImpl<PermissionRoleMapper, PermissionRole> implements IPermissionRoleService {
    /**
     * 获取角色权限
     */
    @Override
    public List<Long> getRolePermission(Long roleId) {
        List<PermissionRole> permissionRoleList = lambdaQuery().eq(PermissionRole::getRoleId, roleId).list();
        return permissionRoleList.stream().map(PermissionRole::getPermissionId).collect(Collectors.toList());
    }

    /**
     * 分配角色权限
     */
    @Override
    public void assignRolePermission(AssignRolePermissionsDTO assignRolePermissionsDTO) {
        //逐个保存
        for (Long permissionId : assignRolePermissionsDTO.getPermissionIds()) {
            PermissionRole one = lambdaQuery().eq(PermissionRole::getRoleId, assignRolePermissionsDTO.getRoleId())
                    .eq(PermissionRole::getPermissionId, permissionId)
                    .one();
            if(one != null){
                continue;
            }
            PermissionRole permissionRole = new PermissionRole(assignRolePermissionsDTO.getRoleId(), permissionId);
            save(permissionRole);
        }
    }
}
